package com.hpin.fansea.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.fansea.R;
import com.hpin.fansea.base.BaseActivity;
import com.hpin.fansea.bean.LoginResult;
import com.hpin.fansea.utils.CommonUtils;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.HttpUtil;
import com.lidroid.xutils.http.RequestParams;

/**
 * 登录页面
 * Created by Aaron on 15/9/7.
 */
public class LoginActivity extends BaseActivity {

    private EditText login_account;
    private EditText login_password;
    private TextView login_forget_password;
    private TextView login_submit;
    private Button login_regist;
    private Button login_visitor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        mApplication.addActivity(this);

        initView();

        login_password.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//				LogUtil.e("login", "onTextChanged==>" + s.toString());
                //以我是乐恵家的密  开头的
                if (s.toString().startsWith(Constant.DEFAULT_PSW_SHORT)) {
                    switch (login_password.getText().toString().trim().length()) {
                        case 9:
                            login_password.setText(login_password.getText().toString().trim().subSequence(8, 9));
                            login_password.setSelection(login_password.length());
                            break;
                        case 7:
                            login_password.setText("");
                            break;

                        default:
                            break;
                    }
                }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
//				LogUtil.e("login", "beforeTextChanged==>" + s);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        communityId = sp.getString(Constant.communityId, "");
        userId = sp.getString(Constant.userId, "");
        psw = sp.getString(Constant.password, "");

        if (!CommonUtils.isNull(userId) && !CommonUtils.isNull(psw)) {
            autoLogin(userId, psw, communityId);
        }
    }

    private void initView() {

        login_account = (EditText) findViewById(R.id.login_account);
        login_password = (EditText) findViewById(R.id.login_password);
        login_forget_password = (TextView) findViewById(R.id.login_forget_password);
        login_submit = (TextView) findViewById(R.id.login_submit);
        login_regist = (Button) findViewById(R.id.login_regist);
        login_visitor = (Button) findViewById(R.id.login_visitor);

        login_forget_password.setOnClickListener(this);
        login_submit.setOnClickListener(this);
        login_regist.setOnClickListener(this);
        login_visitor.setOnClickListener(this);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

//		LogUtil.e("login", "onNewIntent==>");
        login_password.setText(Constant.DEFAULT_PSW);

    }

    /**
     * 检查输入的内容是否为空
     *
     * @return
     */
    public boolean checkInputValue() {

        if (!CommonUtils.isNetworkAvailable(this)) {
            showToast("网络请求失败，请检查您的网络设置");
            return false;
        }
        String phone = login_account.getText().toString().trim();
        String psw = login_password.getText().toString().trim();
        if (CommonUtils.isNull(phone)) {
            showToast("请输入手机号！");
            return false;
        }
        if (!CommonUtils.isPhone(phone)) {
            showToast("请输入正确的手机号！");
            return false;
        }
        if (CommonUtils.isNull(psw)) {
            showToast("请输入密码！");
            return false;
        }
        if (psw.length()<6 || psw.length() > 16) {
            showToast("密码应在6-16位");
            return false;
        }
        return true;
    }

    /**
     * 登录按钮事件
     */
    public void login(String phone, String password, String communityId) {

//        Intent mIntent = new Intent(this, HomeActivity.class);
//        startActivity(mIntent);

        RequestParams params=new RequestParams();
        params.addBodyParameter("lng", "");
        params.addBodyParameter("lat", "");
        params.addBodyParameter("systemType", Constant.SYSTEM_TYPE);// 客户端类型
        params.addBodyParameter("userId", phone);//手机号码
        params.addBodyParameter("password", password);//密码
        params.addBodyParameter("communityId", communityId);//小区ID
        params.addBodyParameter("loginType", Constant.INTERFACE_USERTYPE_NORMAL);//登陆类型(普通用户)

        HttpUtil.getInstance().setPostRequest("登陆中...", this, Constant.WEB_ROOT + Constant.LOGIN, params, new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {

                try {
                    LoginResult loginResult = JSONObject.parseObject(str, LoginResult.class);

                    if (Constant.STATUS_SUCESS.equals(loginResult.status)) {
                        //登陆成功 保存用户数据
                        SharedPreferences.Editor edit = sp.edit();

                        edit.putString(Constant.token, loginResult.token);
                        edit.putString(Constant.communityId, loginResult.userInfo.communityId);
                        edit.putString(Constant.userName, loginResult.userInfo.userName);
                        edit.putString(Constant.userId, loginResult.userInfo.userId);
                        edit.putString(Constant.nickname, loginResult.userInfo.nickname);
                        edit.putString(Constant.headPic, loginResult.userInfo.headPic);
                        edit.putString(Constant.address, loginResult.userInfo.address);
                        edit.putString(Constant.password, loginResult.userInfo.password);
                        edit.putString(Constant.status, loginResult.userInfo.status);
                        edit.putString(Constant.email, loginResult.userInfo.email);
                        edit.putString(Constant.mobile, loginResult.userInfo.mobile);
                        edit.putString(Constant.cityId, loginResult.userInfo.cityId);
                        edit.putString(Constant.projectName, loginResult.userInfo.projectName);
                        edit.putString(Constant.houseCode, loginResult.userInfo.houseCode);
                        edit.putString(Constant.currentCommunityId, loginResult.userInfo.currentCommunityId);
                        edit.putString(Constant.houseId, loginResult.userInfo.houseId);
                        edit.putString(Constant.gender, loginResult.userInfo.gender);
                        edit.putString(Constant.birthday, loginResult.userInfo.birthday);
                        edit.putString(Constant.age, loginResult.userInfo.age);
                        edit.putString(Constant.idNo , loginResult.userInfo.idNo);
                        edit.putString(Constant.cityName, loginResult.userInfo.cityName);
                        edit.putString(Constant.communityName, loginResult.userInfo.communityName);
                        edit.putString(Constant.buildingNo, loginResult.userInfo.buildingNo);
                        edit.putString(Constant.unitNo, loginResult.userInfo.unitNo);
                        edit.putString(Constant.houseNo, loginResult.userInfo.houseNo);

                        edit.commit();

//                         判断小区id为空
                        if (TextUtils.isEmpty(loginResult.userInfo.communityId)) {
                            Intent intent = new Intent(LoginActivity.this, FirstCitySelectActivty.class);
                            startActivity(intent);
                            // finish();
                        } else {
                            Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                            startActivity(intent);
                            // finish();
                        }

                    }else {
                        showToast(loginResult.message);
                    }

                }catch (Exception e) {

                    e.printStackTrace();
                    showToast("登陆失败");
                }

            }
        }, null);

    }

    /**
     * 自动登录
     */
    public void autoLogin(String userId,String password, String communityId) {

        login_account.setText(userId);
        login_password.setText(Constant.DEFAULT_PSW);

        login(userId, password, communityId);

    }

    /**
     * 注册按钮事件
     */
    public void register() {

        Intent intent = new Intent(this, RegistActivity.class);
        startActivity(intent);

    }

    /**
     * 游客按钮事件
     */
    public void visitor() {
        Intent intent = new Intent(this, VisitorActivity.class);
        startActivity(intent);
    }

//    private boolean auto_login;
    private String communityId;
    private String userId;
    private String psw;

    @Override
    protected void onDestroy() {
//        dismissProgress();
        super.onDestroy();
    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {
            case R.id.login_submit://登录

                String loginPsw=Constant.DEFAULT_PSW.equals(login_password.getText().toString().trim())?sp.getString(Constant.password, ""):CommonUtils.toMd5(login_password.getText().toString().trim().getBytes());

                if (checkInputValue())
                    login(login_account.getText().toString().trim(), loginPsw, "");

                break;
            case R.id.login_regist://注册
                register();
                break;
            case R.id.login_visitor://游客登录
                visitor();
                break;
            case R.id.login_forget_password://忘记密码

                Intent intent = new Intent(this, ChangePswActivity.class);
                startActivity(intent);

                break;
        }

    }

}
